package com.idemon.ds.controller;

import java.io.File;

import org.apache.log4j.Logger;

import com.idemon.commons.util.FileKit;
import com.idemon.config.Consts;
import com.idemon.ds.model.Category;
import com.idemon.ds.model.Software;
import com.idemon.ds.model.TypeAndCate;
import com.idemon.ds.model.Userinfo;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;

public class IndexController extends Controller {
	private Logger log = Logger.getLogger(getClass());

	public void index() {
		log.info("截止目前访问人数：" + (Consts.ONLINE_COUNT++));
		render(Consts.DEFAULT_URL_INDEX);
	}

	public void category() {
		int typeid = getParaToInt(0, 1);
		int cid = getParaToInt(1, 1);
		setAttr("pageData", Software.dao.getSoftByTypeAndCate(typeid, cid, 1, 1000));
		setAttr("typeandcate", new TypeAndCate(typeid, cid, Category.dao.findById(cid).getName()));
		render("category.html");
	}

	public void detail() {
		Software soft = Software.dao.findById(getParaToInt(0));
		setAttr("software", soft);
		setAttr("softrelate", Software.dao.getSoft4Relate(soft.getCid()));
		setAttr("typeandcate", new TypeAndCate(soft.getType(), soft.getCid(), soft.getCategory().getName()));
		render("detail.html");
	}

	public void search() {
		setAttr("pageData", Software.dao.getSoftByLike(getPara("key"), 1, 1000));
		setAttr("typeandcate", new TypeAndCate(3, 0, "搜索结果"));
		render("category.html");
	}

	/**
	 * 初始化完毕删除
	 */
	public void manager_software_ui() {
		Object obj = getSessionAttr(Consts.ATTR_KEY_SESSION_USER);
		if (obj == null || !(((Userinfo) obj).getName().equalsIgnoreCase("xiaoxiangzhong"))) {
			redirect("/index");
		} else {
			setAttr("pageData", Software.dao.getAll(1, 2000));
			render("manager_software_ui.html");
		}
	}

	public void upload_logo_ui() {
		Object obj = getSessionAttr(Consts.ATTR_KEY_SESSION_USER);
		if (obj == null || !(((Userinfo) obj).getName().equalsIgnoreCase("xiaoxiangzhong"))) {
			redirect("/index");
		} else {
			int size = PropKit.getInt(Consts.KEY_FILE_UPLOAD_SIZE, Consts.DEFAULT_FILE_UPLOAD_SIZE);
			String encoding = PropKit.get(Consts.KEY_ENCODING, Consts.DEFAULT_ENCODING);
			UploadFile file1 = getFile("logo", "", size, encoding);
			File f1 = file1.getFile();
			String f1Name = FileKit.getNewFileName(f1.getName());
			f1.renameTo(new File(f1.getParent(), f1Name));

			UploadFile file2 = getFile("ui", "", size, encoding);
			File f2 = file2.getFile();
			String f2Name = "_" + FileKit.getNewFileName(f2.getName());
			f2.renameTo(new File(f2.getParent(), f2Name));
			int sid = getParaToInt("sid");
			Software.dao.findById(sid).set("logo", f1Name).set("ui", f2Name).update();
			redirect("/manager_software_ui");
		}
	}
}
